<script setup lang="ts">
import type { FormType } from './components/order';

import { computed, onMounted, onUnmounted, ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';

import { DownOutlined } from '@ant-design/icons-vue';
import { Dropdown, Menu, MenuItem, Spin } from 'ant-design-vue';

import { getCountResp, getOrderDetail, getOrderList } from '#/api';

import OrderDetails from './components/OrderDetails.vue';
import OrderHead from './components/OrderHead.vue';
import OrderList from './components/OrderList.vue';
// 头部筛选
const form = ref<FormType>({
  tabState: 1, // tab上的订单状态
  orderNo0rName: '', // 订单号或订单名称
  dateType: 1, // 日期类型
  startDate: '',
  endDate: '',
  orderType: '', // 订单类型
  orderState: '', // 订单状态
  roomType: '', // 房型
  timeSort: 1, // 时间排序
});

const loading = ref(true);
// 引用 main 元素
const mainRef = ref<HTMLElement | null>(null);
// 存储 main 盒子的高度
const mainHeight = ref<number>(0);

// 获取 main 盒子高度的函数
const getMainHeight = () => {
  if (mainRef.value) {
    mainHeight.value = mainRef.value.offsetHeight;
  }
};
// 分页
const pageNo = ref<number>(1);
// 订单总数量
const total = ref<number>(0);

interface OrderItem {
  bedType: string;
  breakfastCount: number;
  checkInDate: string;
  checkOutDate: string;
  contactName: string;
  createTime: string;
  hotelId: number;
  nameZh: string;
  nights: number;
  orderNo: string;
  orderStatus: number;
  payAmount: number;
  payStatus: number;
  roomCount: number;
}
// 订单列表
const orderList = ref<OrderItem[]>([]);
// 当前查看的订单ID
const currentOrderId = ref<string | undefined>('');
// 订单详情数据
const orderData = ref();

// 订单排序
const optionsTimeSort = ref([
  {
    label: '通知时间排序',
    value: 1,
  },
  {
    label: '入住时间排序',
    value: 2,
  },
  {
    label: '离店时间排序',
    value: 3,
  },
]);
// 取消和修改订单查看状态 根据订单详情orderType状态判断  2修改： modify  4取消:  cancel
const orderDetSeeState = ref('');

// 获取订单详情数据接口请求
const getOrderData = async () => {
  if (!currentOrderId.value) return;
  try {
    const { data } = await getOrderDetail({
      orderNo: currentOrderId.value,
    });
    orderData.value = data || {};
    // 防止订单又有修改又有取消的情况
    if ((data.orderType === 2 || data.orderChangeLog) && data.orderType !== 4) {
      orderDetSeeState.value = 'modify';
    } else if (data.orderType === 4 || data.applyCancelTime) {
      orderDetSeeState.value = 'cancel';
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error('获取详情错误：', error);
  }
};

const timeType = computed(() => {
  switch (form.value.tabState.toString()) {
    case '': {
      return form.value.dateType;
    }
    case '4': {
      return 1;
    }
    case '5': {
      return 2;
    }
    default: {
      return null;
    }
  }
});
const countTotal = ref({
  checkInOrderNum: 0,
  newOrderNum: 0,
  pendingCheckInOrderNum: 0,
  unhandledOrderNum: 0,
});
const getCount = async () => {
  try {
    const { data } = await getCountResp();
    countTotal.value = data;
  } catch (error) {
    console.error('获取统计失败：', error);
  }
};

// 更新订单列表
const upGetList = async () => {
  orderData.value = {};
  currentOrderId.value = '';
  orderList.value = [];
  pageNo.value = 1;
  orderDetSeeState.value = '';

  // eslint-disable-next-line no-use-before-define
  await getList();
  await getCount();
};

// 更新列表和订单详情数据
const upOrderData = async (orderNo: string) => {
  await getOrderData();
  const index = orderList.value.findIndex((item) => item.orderNo === orderNo);
  if (index === -1) return;
  const { data } = await getOrderList({
    pageNo: index + 1,
    pageSize: 1,
    startTime:
      [1, 2, 3].includes(form.value.tabState) || !form.value.startDate
        ? ''
        : form.value.startDate,
    endTime:
      [1, 2, 3].includes(form.value.tabState) || !form.value.endDate
        ? ''
        : form.value.endDate,
    orderNoOrName: form.value.orderNo0rName || '',
    orderType: form.value.orderType || null,
    orderTalStatus: form.value.tabState || null,
    orderTimeType: timeType.value,
    orderSortType: form.value.timeSort || 1,
    orderStatus:
      form.value.tabState === 5 ||
      form.value.orderState === 31 ||
      !form.value.orderState
        ? null
        : form.value.orderState,
  });
  // 如果满足则替换内容，否则删除
  if (data.records.length > 0 && orderNo === data.records[0].orderNo) {
    orderList.value.splice(index, 1, data.records[0]); // 更新订单列表指定内容
  } else {
    orderList.value.splice(index, 1); // 删除订单列表指定内容
    // 更新选中的订单以及订单详情数据
    if (orderNo === currentOrderId.value && orderList.value.length > 0) {
      loading.value = true;
      currentOrderId.value = orderList.value[0]?.orderNo || '';
      await getOrderData();
    } else if (orderList.value.length === 0) {
      await upGetList();
    }
  }
  await getCount();
};

// 获取订单列表
const getList = async () => {
  if (total.value !== 0 && total.value === orderList.value.length) {
    return;
  }
  try {
    const { data } = await getOrderList({
      pageNo: pageNo.value,
      pageSize: 20,
      startTime:
        [1, 2, 3].includes(form.value.tabState) || !form.value.startDate
          ? ''
          : form.value.startDate,
      endTime:
        [1, 2, 3].includes(form.value.tabState) || !form.value.endDate
          ? ''
          : form.value.endDate,
      orderNoOrName:
        form.value.tabState === 1 ? '' : form.value.orderNo0rName || '',
      orderType:
        form.value.tabState === 1 ? null : form.value.orderType || null,
      orderTalStatus: form.value.tabState || null,
      orderTimeType: timeType.value,
      orderSortType:
        form.value.tabState === 1 ? null : form.value.timeSort || 1,
      orderStatus:
        [1, 5].includes(form.value.tabState) || !form.value.orderState
          ? null
          : form.value.orderState,
    });
    total.value = data.total || 0;
    orderList.value = [...orderList.value, ...data.records];
    if (total.value === 0 && orderList.value.length === 0) {
      loading.value = false;
    }
    if (currentOrderId.value && orderList.value.length > 0) {
      const found = orderList.value.find(
        (item) => item.orderNo === currentOrderId.value,
      );
      if (found) {
        orderDetSeeState.value = '';
        getOrderData();
      }
    } else if (!currentOrderId.value && orderList.value.length > 0) {
      currentOrderId.value = orderList.value[0]?.orderNo || '';
      orderDetSeeState.value = '';
      getOrderData();
    }
  } catch (error) {
    loading.value = false;
    console.error('获取待确认订单失败：', error);
  }
};

// 左侧滚动触底事件
const getLeftScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  if (target.scrollTop + target.clientHeight >= target.scrollHeight) {
    pageNo.value++;
    getList();
  }
};

// 订单列表上的排序切换
const handleTimeSort = (value: number | string) => {
  if (form.value.timeSort === value) {
    return;
  }
  loading.value = true;
  form.value.timeSort = value;
  upGetList();
};

// 切换选中的订单id
const goDetail = (orderId: string) => {
  currentOrderId.value = orderId;
  orderData.value = {};
  loading.value = true;
  orderDetSeeState.value = '';
  getOrderData();
};

const changleTab = () => {
  loading.value = true;
  upGetList();
};

// 在onMounted前添加保存状态的函数
const saveStateToStorage = () => {
  localStorage.setItem(
    'orderListState',
    JSON.stringify({
      form: form.value,
      currentOrderId: currentOrderId.value,
    }),
  );
};

onMounted(() => {
  const savedState = localStorage.getItem('orderListState');
  if (savedState) {
    try {
      const { form: savedForm, currentOrderId: savedOrderId } =
        JSON.parse(savedState);
      form.value = { ...form.value, ...savedForm };
      currentOrderId.value = savedOrderId;
    } catch (error) {
      console.error('Failed to parse saved state', error);
    }
  }
  getCount();
  getList();
  // 初始化获取高度
  getMainHeight();
  // 监听窗口大小变化事件
  window.addEventListener('resize', getMainHeight);
  // 添加beforeunload事件监听器保存状态
  window.addEventListener('beforeunload', saveStateToStorage);
  // 监听全局是否出发订单通知
  window.addEventListener('order-list-update', upGetList);
});

onUnmounted(() => {
  // 移除窗口大小变化事件监听，避免内存泄漏
  window.removeEventListener('resize', getMainHeight);
  window.removeEventListener('beforeunload', saveStateToStorage);
  localStorage.removeItem('orderListState');
  window.removeEventListener('order-list-update', upGetList);
});

onBeforeRouteLeave(() => {
  localStorage.removeItem('orderListState');
});
</script>

<template>
  <div
    class="absolute bottom-0 right-0 flex h-[100%] w-[100%] flex-col overflow-hidden"
  >
    <div
      id="main"
      ref="mainRef"
      :class="[orderList.length > 0 ? 'overflow-auto' : 'overflow-hidden']"
      class="h-[100%] w-[100%]"
    >
      <!-- 头部tab以及筛选 -->
      <div class="min-w-[1050px] 2xl:min-w-[1280px]">
        <OrderHead
          v-model:form="form"
          :count-total="countTotal"
          @up-list="changleTab"
        />
      </div>
      <!-- 底部订单主体页面 -->
      <div class="relative flex">
        <!-- 左侧订单列表 -->
        <div
          :style="{ height: `${mainHeight}px` }"
          class="main-left sticky top-0 z-[10] min-w-[388px] overflow-auto px-3 2xl:min-w-[448px]"
          @scroll="getLeftScroll"
        >
          <div
            class="card-box flex h-[32px] items-center justify-between rounded-sm border-none px-3"
          >
            <div>
              <span class="text-primary">{{ total || 0 }}</span>
              <span>条订单</span>
            </div>
            <Dropdown
              v-if="form.tabState !== 1"
              :trigger="['click']"
              placement="bottomRight"
            >
              <a class="flex items-center" @click.prevent>
                <p>
                  {{
                    optionsTimeSort.filter(
                      (item) => item.value === form.timeSort,
                    )[0]?.label || ''
                  }}
                </p>
                <DownOutlined class="ml-1 text-xs" />
              </a>
              <template #overlay>
                <Menu>
                  <MenuItem
                    v-for="item in optionsTimeSort"
                    :key="item.value"
                    @click="handleTimeSort(item.value)"
                  >
                    {{ item.label }}
                  </MenuItem>
                </Menu>
              </template>
            </Dropdown>
          </div>
          <div v-for="item in orderList" :key="item.orderNo">
            <OrderList
              v-model:order-det-see-state="orderDetSeeState"
              :current-order-id="currentOrderId"
              :data="item"
              :form="form"
              :order-data="orderData"
              @click="goDetail"
              @switch-status="
                (e) => {
                  orderDetSeeState = e;
                }
              "
            />
          </div>
          <div
            v-if="total <= orderList.length"
            class="py-3 text-center text-xs opacity-60"
          >
            没有更多订单了~
          </div>
        </div>
        <!-- 右侧订单详情 -->
        <div class="relative min-w-[662px] flex-auto 2xl:min-w-[832px]">
          <div
            v-if="loading"
            class="z-100 absolute left-0 top-0 flex h-full w-full flex-auto items-center justify-center bg-white"
          >
            <Spin size="large" />
          </div>
          <OrderDetails
            v-else
            :data="orderData"
            :tab-state="form.tabState"
            :total="total"
            :type="orderDetSeeState"
            @up-order-data="upOrderData"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.main-left::-webkit-scrollbar-thumb {
  background-color: #e3e3e3; /* 滑块背景颜色 */
}
</style>
